import ma.const
import ma.utils.location
from ma.utils.clustersetup import CLUSTER_IPS

import os
import sys
import getopt

ma_stats_filename = 'ma_stats.csv'
log_filename = 'ma_logger.log'
master_log_filename = 'ma_master.log'
estimator_filename = 'estimator_stats.csv'
threshold_filename = 'threshold_stats.csv'
nohup_out_filename = 'nohup.out'

nohup_exec_path = 'nohup'
python_exec_path = ma.const.XmlData.get_filepath_str_data(ma.const.xml_python_exec) + ' -u'
mr_exec_path = os.path.join(ma.utils.location.get_mrimprov_path(), 'core', 'nodetracker.py')
mr_remote_exec_path = os.path.join(ma.utils.location.get_scripts_path(), 'runscript+.py')

optlist, args = getopt.getopt(sys.argv[1:], 'rns')
start_remote = False
start_on_nohup = False
silent_mode = False
for opt in optlist:
    if opt[0] == '-r':
        start_remote = True
    elif opt[0] == '-n':
        start_on_nohup = True
    elif opt[0] == '-s':
        silent_mode = True
        
if not silent_mode: print('usage: python runscript+.py [-r to start on all remote machines] [-n use nohup] [job_id]')

if not silent_mode: print("Deleting log files")
os.system('rm -f ' + ma_stats_filename)
os.system('rm -f ' + log_filename)
os.system('rm -f ' + master_log_filename)
os.system('rm -f ' + estimator_filename)
os.system('rm -f ' + threshold_filename)
os.system('rm -f ' + nohup_out_filename)

nodetracker_cmd = python_exec_path + ' ' + mr_exec_path 
remote_cmd = python_exec_path + ' ' + mr_remote_exec_path + ' -s'

# if job id given 
if len(args) == 1:
    forced_job_id = int(args[0])

    if not silent_mode: print('deleting local temp dirs')
    local_fs_input_path = ma.const.JobsXmlData.get_filepath_str_data(ma.const.xml_local_input_temp_dir, forced_job_id)
    local_fs_output_path = ma.const.JobsXmlData.get_filepath_str_data(ma.const.xml_local_output_temp_dir, forced_job_id)
    os.system('rm -r -f ' + os.path.join(local_fs_input_path, '*'))
    os.system('rm -r -f ' + os.path.join(local_fs_output_path, '*'))
    
    if not silent_mode: print('Forcing job-id', forced_job_id)
    
    nodetracker_cmd = nodetracker_cmd + ' ' + str(forced_job_id)
    remote_cmd = remote_cmd + ' ' + str(forced_job_id)

# if this needs to be started immune to hangups
if start_on_nohup:
    nodetracker_cmd = nohup_exec_path + ' ' + nodetracker_cmd + ' > ' + nohup_out_filename
    remote_cmd = remote_cmd + ' -n'
elif silent_mode:
    nodetracker_cmd = nodetracker_cmd + ' > ' + nohup_out_filename


# starting remote servers
if start_remote:
    for ip in CLUSTER_IPS:
        os.system('ssh ' + ip + ' ' + remote_cmd)
        if not silent_mode: print("Started MR+ NT (Master-less) at " + ip)

# starting nodetracker
if not silent_mode: print("\\\\ --- Starting MR+ NT (Master-less) --- //")
if not silent_mode: print("Executing ->", nodetracker_cmd)
os.system(nodetracker_cmd + ' &')

time.sleep(2)

if start_on_nohup and not silent_mode:
    os.system('tail -f ' + nohup_out_filename)
